<?php

require_once(WSB_XTENSION_PATH . 'simpleshop/models/DbTable/Basket/Table.php');
require_once(WSB_XTENSION_PATH . 'simpleshop/models/DbTable/Order/Table.php');
require_once(WSB_XTENSION_PATH . 'simpleshop/models/DbTable/Order/Item/Table.php');

class Simpleshop_CheckoutController extends WSB_Xtension_Extension
{

	public function init()
	{
		$this->_translate = Zend_Registry::get('Zend_Translate');
		$locale = Zend_Registry::get('Zend_Locale');
		$translation = WSB_APP_PATH . 'i18n/validate.' . $locale.'.csv';
		if(is_file($translation)) {
			$this->_translate->addTranslation($translation, $locale);
		}
		Zend_Form::setDefaultTranslator($this->_translate);

	}

	public function indexAction()
	{

		$config = $this->getConfiguration();
		$shippingAndHandlingCosts = floatval($config->shippingAndHandlingCosts);

		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();

		$this->_view->minimumOrderValue = floatval($config->minimumOrderValue);
		$this->_view->isValidMinimumOrderValue = $this->_isValidMinimumOrderValue();
		$this->_view->shippingAndHandlingCosts = $shippingAndHandlingCosts;
		$this->_view->rowset = $rowset;
		$this->_view->total = $rowset->getTotalPrice($shippingAndHandlingCosts);
		$this->_view->currency = $config->currency;

		$this->addContent($this->_view->render('checkout/index.phtml'));
	}

	public function emptyAction()
	{
		$sessionId = Zend_Session::getId();
		if(!empty($sessionId)) {
			$table = new Simpleshop_Model_DbTable_Basket_Table();
			$db = $table->getAdapter();
			$data = array(
				'deleted' => 1,
				'modified' => time()
			);
			$where = array();
			$where[] = $db->quoteInto('session_id = ?', $sessionId);
			$table->update($data, $where);

			// Wird zur Zeit nur benoetigt, um das Caching auszuschalten.
			$session = new Zend_Session_Namespace('Simpleshop_Xtension');
			$session->unsetAll();

		}
		$this->indexAction();
	}

	private function _getSessionParam($key)
	{
		$session = new Zend_Session_Namespace('Simpleshop_Model_DbTable_Checkout');
		return isset($session->$key) ? $session->$key : null ;
	}

	private function _isValidMinimumOrderValue()
	{
		$config = $this->getConfiguration();
		$minimumOrderValue = floatval($config->minimumOrderValue);
		if(empty($minimumOrderValue)) {
			return true;
		}
		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();
		$total = floatval($rowset->getTotalPrice());
		if($total > $minimumOrderValue) {
			return true;
		}
		return false;
	}

	public function step1Action()
	{

		// Bei leerem Warenkorb zur indexAction
		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();
		if($rowset->count() == 0) {
			$this->indexAction();
			return;
		}

		// Mindestbestellwert
		if(!$this->_isValidMinimumOrderValue()) {
			$this->indexAction();
			return;
		}

		$request = $this->getRequest();
		$session = new Zend_Session_Namespace('Simpleshop_Model_DbTable_Checkout');

		$elements = array();
		$elements['ia_title']['type'] = 'select';
		$elements['ia_title']['options']['label'] = 'Anrede';
		$elements['ia_title']['options']['value'] = $this->_getSessionParam('ia_title');
		$elements['ia_title']['options']['multiOptions'][''] = '';
		$elements['ia_title']['options']['multiOptions']['Frau'] = 'Frau';
		$elements['ia_title']['options']['multiOptions']['Herr'] = 'Herr';
		$elements['ia_title']['options']['multiOptions']['Firma'] = 'Firma';
		$elements['ia_title']['options']['multiOptions']['Herr und Frau'] = 'Herr und Frau';
		$elements['ia_title']['options']['multiOptions']['Familie'] = 'Familie';
		$elements['ia_title']['options']['required'] = true;

		$elements['ia_company']['type'] = 'text';
		$elements['ia_company']['options']['label'] = 'Firma';
		$elements['ia_company']['options']['value'] = $this->_getSessionParam('ia_company');

		$elements['ia_first_name']['type'] = 'text';
		$elements['ia_first_name']['options']['label'] = 'Vorname';
		$elements['ia_first_name']['options']['value'] = $this->_getSessionParam('ia_first_name');
		$elements['ia_first_name']['options']['required'] = true;

		$elements['ia_last_name']['type'] = 'text';
		$elements['ia_last_name']['options']['label'] = 'Name';
		$elements['ia_last_name']['options']['value'] = $this->_getSessionParam('ia_last_name');
		$elements['ia_last_name']['options']['required'] = true;

		$elements['ia_additional']['type'] = 'text';
		$elements['ia_additional']['options']['label'] = 'Zusatz';
		$elements['ia_additional']['options']['value'] = $this->_getSessionParam('ia_additional');

		$elements['ia_street']['type'] = 'text';
		$elements['ia_street']['options']['label'] = 'Strasse';
		$elements['ia_street']['options']['value'] = $this->_getSessionParam('ia_street');
		$elements['ia_street']['options']['required'] = true;

		$elements['ia_zip']['type'] = 'text';
		$elements['ia_zip']['options']['label'] = 'PLZ';
		$elements['ia_zip']['options']['value'] = $this->_getSessionParam('ia_zip');
		$elements['ia_zip']['options']['required'] = true;

		$elements['ia_location']['type'] = 'text';
		$elements['ia_location']['options']['label'] = 'Ort';
		$elements['ia_location']['options']['value'] = $this->_getSessionParam('ia_location');
		$elements['ia_location']['options']['required'] = true;

		$elements['ia_country']['type'] = 'select';
		$elements['ia_country']['options']['label'] = 'Land';
		$elements['ia_country']['options']['value'] = $this->_getSessionParam('ia_country');
		$elements['ia_country']['options']['multiOptions'][''] = '';
		$elements['ia_country']['options']['multiOptions']['CH'] = 'Schweiz';
		$elements['ia_country']['options']['required'] = true;

		$elements['ia_email']['type'] = 'text';
		$elements['ia_email']['options']['label'] = 'E-mail';
		$elements['ia_email']['options']['value'] = $this->_getSessionParam('ia_email');
		$elements['ia_email']['options']['required'] = true;

		$elements['ia_phone']['type'] = 'text';
		$elements['ia_phone']['options']['label'] = 'Telefon';
		$elements['ia_phone']['options']['value'] = $this->_getSessionParam('ia_phone');
		$elements['ia_phone']['options']['required'] = true;

		$elements['postal_address']['type'] = 'radio';
		$elements['postal_address']['options']['label'] = 'Lieferadresse identisch?';
		$elements['postal_address']['options']['value'] = $this->_getSessionParam('postal_address');
		$elements['postal_address']['options']['multiOptions']['0'] = 'Ja';
		$elements['postal_address']['options']['multiOptions']['1'] = 'Nein';
		//$elements['postal_address']['options']['required'] = true;

		$elements['submit_step1']['type'] = 'submit';
		$elements['submit_step1']['options']['label'] = 'Weiter';

		$url = WSB_Xtension_Url::getInstance();
		$configArray = array();
		$configArray['action'] = $url->getHrefToThisPage(array('simpleshop_checkout' => array('action' => 'step1')));
		$configArray['method'] = 'post';
		$configArray['elements'] = $elements;

		$config = new Zend_Config($configArray);
		$form = new Zend_Form($config);

		if($request->isPost() && ($request->getPost('submit_step1') != '') && $form->isValid($_POST)) {
			foreach($request->getPost() AS $key=>$value) {
				$session->$key = $value;
			}
			// Submit loeschen
			unset($session->submit_step1);
			if((int)$request->getPost('postal_address') > 0) {
				$this->step2Action();
			} else {
				$this->step3Action();
			}
		} else {
			$this->_view->form = $form;
			$this->addContent($this->_view->render('checkout/step1.phtml'));
		}

	}

	public function step2Action()
	{

		// Bei leerem Warenkorb zur indexAction
		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();
		if($rowset->count() == 0) {
			$this->indexAction();
			return;
		}

		// Mindestbestellwert
		if(!$this->_isValidMinimumOrderValue()) {
			$this->indexAction();
			return;
		}

		$request = $this->getRequest();
		$session = new Zend_Session_Namespace('Simpleshop_Model_DbTable_Checkout');

		$elements = array();
		$elements['pa_title']['type'] = 'select';
		$elements['pa_title']['options']['label'] = 'Anrede';
		$elements['pa_title']['options']['value'] = $this->_getSessionParam('pa_title');
		$elements['pa_title']['options']['multiOptions'][''] = '';
		$elements['pa_title']['options']['multiOptions']['Frau'] = 'Frau';
		$elements['pa_title']['options']['multiOptions']['Herr'] = 'Herr';
		$elements['pa_title']['options']['multiOptions']['Firma'] = 'Firma';
		$elements['pa_title']['options']['multiOptions']['Herr und Frau'] = 'Herr und Frau';
		$elements['pa_title']['options']['multiOptions']['Familie'] = 'Familie';
		$elements['pa_title']['options']['required'] = true;

		$elements['pa_first_name']['type'] = 'text';
		$elements['pa_first_name']['options']['label'] = 'Vorname';
		$elements['pa_first_name']['options']['value'] = $this->_getSessionParam('pa_first_name');
		$elements['pa_first_name']['options']['required'] = true;

		$elements['pa_last_name']['type'] = 'text';
		$elements['pa_last_name']['options']['label'] = 'Name';
		$elements['pa_last_name']['options']['value'] = $this->_getSessionParam('pa_last_name');
		$elements['pa_last_name']['options']['required'] = true;

		$elements['pa_additional']['type'] = 'text';
		$elements['pa_additional']['options']['label'] = 'Zusatz';
		$elements['pa_additional']['options']['value'] = $this->_getSessionParam('pa_additional');

		$elements['pa_street']['type'] = 'text';
		$elements['pa_street']['options']['label'] = 'Strasse';
		$elements['pa_street']['options']['value'] = $this->_getSessionParam('pa_street');
		$elements['pa_street']['options']['required'] = true;

		$elements['pa_zip']['type'] = 'text';
		$elements['pa_zip']['options']['label'] = 'PLZ';
		$elements['pa_zip']['options']['value'] = $this->_getSessionParam('pa_zip');
		$elements['pa_zip']['options']['required'] = true;

		$elements['pa_location']['type'] = 'text';
		$elements['pa_location']['options']['label'] = 'Ort';
		$elements['pa_location']['options']['value'] = $this->_getSessionParam('pa_location');
		$elements['pa_location']['options']['required'] = true;

		$elements['pa_country']['type'] = 'select';
		$elements['pa_country']['options']['label'] = 'Land';
		$elements['pa_country']['options']['value'] = $this->_getSessionParam('pa_country');
		$elements['pa_country']['options']['multiOptions'][''] = '';
		$elements['pa_country']['options']['multiOptions']['CH'] = 'Schweiz';
		$elements['pa_country']['options']['required'] = true;

		$elements['submit_step2']['type'] = 'submit';
		$elements['submit_step2']['options']['label'] = 'Weiter';

		$url = WSB_Xtension_Url::getInstance();
		$configArray = array();
		$configArray['action'] = $url->getHrefToThisPage(array('simpleshop_checkout' => array('action' => 'step2')));
		$configArray['method'] = 'post';
		$configArray['elements'] = $elements;

		$config = new Zend_Config($configArray);
		$form = new Zend_Form($config);

		if($request->isPost() && ($request->getPost('submit_step2') != '') && $form->isValid($_POST)) {
			foreach($request->getPost() AS $key=>$value) {
				$session->$key = $value;
			}
			// Submit loeschen
			unset($session->submit_step2);
			$this->step3Action();
		} else {
			$this->_view->form = $form;
			$this->addContent($this->_view->render('checkout/step2.phtml'));
		}

	}

	public function step3Action()
	{

		// Bei leerem Warenkorb zur indexAction
		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();
		if($rowset->count() == 0) {
			$this->indexAction();
			return;
		} else {

			$config = $this->getConfiguration();
			$shippingAndHandlingCosts = floatval($config->shippingAndHandlingCosts);

			$this->_view->shippingAndHandlingCosts = $shippingAndHandlingCosts;
			$this->_view->rowset = $rowset;
			$this->_view->total = $rowset->getTotalPrice($shippingAndHandlingCosts);
			$this->_view->currency = $config->currency;

		}

		// Mindestbestellwert
		if(!$this->_isValidMinimumOrderValue()) {
			$this->indexAction();
			return;
		}

		$request = $this->getRequest();
		$session = new Zend_Session_Namespace('Simpleshop_Model_DbTable_Checkout');

		$elements = array();
		$elements['payment_method']['type'] = 'select';
		$elements['payment_method']['options']['label'] = 'Zahlungsart';
		$elements['payment_method']['options']['value'] = $this->_getSessionParam('payment_method');
		$elements['payment_method']['options']['multioptions'][''] = '';
		$elements['payment_method']['options']['multioptions']['invoice'] = 'Rechnung';
		$elements['payment_method']['options']['multioptions']['prepayment'] = 'Vorauskasse';
		$elements['payment_method']['options']['multioptions']['cod'] = 'Nachnahme';
		$elements['payment_method']['options']['required'] = true;

		$elements['terms_and_conditions']['type'] = 'multiCheckbox';
		$elements['terms_and_conditions']['options']['label'] = 'AGB';
		$elements['terms_and_conditions']['options']['multioptions']['agb'] = 'Ja, ich akzeptiere die allgemeinen Geschäftsbedingungen (AGB)';
		$elements['terms_and_conditions']['options']['required'] = true;

		$elements['submit_step3']['type'] = 'submit';
		$elements['submit_step3']['options']['label'] = 'Bestellung abschliessen';

		$url = WSB_Xtension_Url::getInstance();
		$configArray = array();
		$configArray['action'] = $url->getHrefToThisPage(array('simpleshop_checkout' => array('action' => 'step3')));
		$configArray['method'] = 'post';
		$configArray['elements'] = $elements;

		$config = new Zend_Config($configArray);
		$form = new Zend_Form($config);

		if($request->isPost() && ($request->getPost('submit_step3') != '') && $form->isValid($_POST)) {
			foreach($request->getPost() AS $key=>$value) {
				$session->$key = $value;
			}
			// Submit loeschen
			unset($session->submit_step3);
			$this->step4Action();
		} else {
			$this->_view->form = $form;

			foreach($session AS $key=>$val) {
				$this->_view->$key = $val;
			}

			$this->addContent($this->_view->render('checkout/step3.phtml'));
		}

	}

	/**
	 * @todo: Validierung und direkter Aufruf verhindern!!!
	 *
	 */
	public function step4Action()
	{

		$session = new Zend_Session_Namespace('Simpleshop_Model_DbTable_Checkout');
		$config = $this->getConfiguration();
		$shippingAndHandlingCosts = floatval($config->shippingAndHandlingCosts);

		// Bei leerem Warenkorb zur indexAction
		$table = new Simpleshop_Model_DbTable_Basket_Table();
		$rowset = $table->getRowset();
		if($rowset->count() == 0) {
			$this->indexAction();
			return;
		} else {

			// Mindestbestellwert
			if(!$this->_isValidMinimumOrderValue()) {
				$this->indexAction();
				return;
			}

			$error = false;

			// Order
			$set = array();
			$set['currency'] = $config->currency;
			$set['total_excl'] = $rowset->getTotalPrice();
			$set['shipping_and_handling_costs'] = $shippingAndHandlingCosts;
			foreach($session AS $key=>$value) {
				if(!in_array($key, array('terms_and_conditions'))) {
					$set[$key] = $value;
				}
			}
			$table = new Simpleshop_Model_DbTable_Order_Table();
			$order = $table->createRow($set);
			$orderId = $order->save();

			if(empty($orderId)) {
				$error = true;
			} else {

				// View
				$this->_view->orderId = $orderId;
				$this->_view->shippingAndHandlingCosts = $shippingAndHandlingCosts;

				foreach($session AS $key=>$val) {
					$this->_view->$key = $val;
				}

				// Orderitems
				foreach($rowset AS $row) {
					$set = array();
					$set['order_id'] = $orderId;
					$set['article_id'] = $row->getArticleId();
					$set['article_number'] = $row->getArticleNumber();
					$set['title'] = $row->getArticleTitle();
					$set['quantity'] = $row->getQuantity();
					$set['price'] = $row->getPrice();

					$table = new Simpleshop_Model_DbTable_Order_Item_Table();
					$row = $table->createRow($set);
					$orderItemId = $row->save();

					if(empty($orderItemId)) {
						$error = true;
						break;
					}

				}

				// Basket und Session loeschen
				if(!$error) {

					// Warenkorbeintraege als "bestellt" markieren
					$table = new Simpleshop_Model_DbTable_Basket_Table();
					$rowset = $table->getRowset();
					foreach($rowset AS $row) {
						$row->ordered = 1;
						$row->save();
					}

					// Wird zur Zeit nur benoetigt, um das Caching auszuschalten.
					$session = new Zend_Session_Namespace('Simpleshop_Xtension');
					$session->unsetAll();

				}

				// Mailtext als UTF-8?
				$bodyHtml = $this->_view->render('checkout/mail_html.phtml');

				$mail = new Zend_Mail('utf-8');
				$mail->setBodyText(strip_tags($bodyHtml));
				$mail->setBodyHtml($bodyHtml);
				$mail->setFrom('do-not-reply@zephir.ch', 'Test');
				$mail->addTo($order->ia_email, $order->ia_first_name . ' ' . $order->ia_last_name);
				$mail->setSubject('Ihre Bestellung');

				if(!empty($config->smtpServer) && !empty($config->smtpUsername) && !empty($config->smtpPassword)) {
					$transport = new Zend_Mail_Transport_Smtp(
						$config->smtpServer,
						array(
							'auth' => 'login',
			                'username' => $config->smtpUsername,
			                'password' => $config->smtpPassword
						)
					);
					$mail->send($transport);
				} else {
					$mail->send();
				}


			}

			$this->addContent($this->_view->render('checkout/step4.phtml'));

		}


	}

}
